package com.dy.user.controller;

import com.dy.basic.util.AjaxResult;
import com.dy.basic.util.PageList;
import com.dy.user.domain.User;
import com.dy.user.dto.EmailRegisterFormDto;
import com.dy.user.dto.PhoneRegisterFormDto;
import com.dy.user.query.UserQuery;
import com.dy.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if( user.getId()!=null)
                userService.update(user);
            else
                userService.add(user);
            return AjaxResult.me().success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxResult.me().success();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().fail();
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public User get(@PathVariable("id")Long id)
    {
        return userService.findById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<User> list(){

        return userService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<User> json(@RequestBody UserQuery query)
    {
        return userService.queryByPage(query);
    }


    /**
     * 添加手机用户注册数据
     */
    @PostMapping("/phoneRegister")
    public AjaxResult phoneRegister(@RequestBody PhoneRegisterFormDto phoneRegisterFormDto)
    {
        try {
            userService.addByPhone(phoneRegisterFormDto);
            return AjaxResult.me().setSuccess(true).setMsg("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setResultObj("网络异常");
        }
    }


    /**
     * 添加邮箱注册用户数据
     */
    @PostMapping("/emailRegister")
    public AjaxResult emailRegister(@RequestBody EmailRegisterFormDto emailRegisterFormDto)
    {
        try {
            userService.addByEmail(emailRegisterFormDto);
            return AjaxResult.me().setSuccess(true).setMsg("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setResultObj("网络异常");
        }
    }

}
